/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.imenu.ejb;

import com.imenu.entity.ImenuCourse;
import com.imenu.entity.ImenuMenu;
import com.imenu.entity.ImenuTag;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.Query;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Yunzi
 */
@Stateless
public class ImenuCourseFacade extends AbstractFacade<ImenuCourse> {

    @EJB
    ImenuMenuFacade menuFacade;
    
    @PersistenceContext(unitName = "iMenuPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }
    
    @Override
    public void create(ImenuCourse entity) {
        entity.getMenu().setUpdateTime(new java.util.Date(System.currentTimeMillis()));
        super.create(entity);
    }

    @Override
    public void edit(ImenuCourse entity) {
        entity.getMenu().setUpdateTime(new java.util.Date(System.currentTimeMillis()));
        super.edit(entity);
    }

    @Override
    public void remove(ImenuCourse entity) {
       entity.getMenu().setUpdateTime(new java.util.Date(System.currentTimeMillis()));
       super.remove(entity);
    }

    public ImenuCourseFacade() {
        super(ImenuCourse.class);
    }

    public Long count(ImenuMenu menu) {
        return (Long) getEntityManager().createNamedQuery("ImenuCourse.countByMenu").setParameter("menu", menu).getSingleResult();
    }
    
    public List<ImenuCourse> findByMenu(ImenuMenu menu) {
        return  getEntityManager().createNamedQuery("ImenuCourse.findByMenu").setParameter("menu", menu).getResultList();
    }
    
    public List<ImenuCourse> findByTag(ImenuTag tag) {
        return  getEntityManager().createQuery("SELECT i FROM ImenuCourse i WHERE i.tag = :tag").setParameter("tag", tag).getResultList();
    }

    public List<ImenuMenu> findRange(int[] range, ImenuMenu menuId) {
        Query q = getEntityManager().createNamedQuery("ImenuCourse.findByMenuId");
        q.setParameter("menuId", menuId);
        return q.getResultList();
    }
}
